const axios = require('axios');

// 测试配置
const BASE_URL = 'http://localhost:3000';

async function testExpensesStats() {
    try {
        console.log('🚀 开始测试 Expenses API 统计信息...\n');

        // 测试获取费用记录列表（不需要认证，先测试基本功能）
        console.log('📋 测试获取费用记录列表...');

        // 注意：这里需要有效的认证token和车辆ID
        // 如果你有测试数据，请更新下面的参数
        const response = await axios.get(`${BASE_URL}/api/expenses`, {
            headers: {
                'Authorization': 'Bearer YOUR_TEST_TOKEN_HERE', // 需要替换为实际的测试token
                'Content-Type': 'application/json'
            },
            params: {
                page: 1,
                limit: 10,
                // vehicleId: 'your-vehicle-id' // 可选：指定车辆ID
            }
        });

        if (response.status === 200) {
            console.log('✅ 获取费用记录列表成功');
            console.log('📊 响应数据结构:');

            const { expenses, pagination } = response.data.data;

            console.log(`📄 总记录数: ${pagination.total}`);
            console.log(`📄 当前页记录数: ${expenses.length}`);

            // 检查时间戳字段和统计信息
            expenses.forEach((expense, index) => {
                console.log(`\n📝 记录 ${index + 1}:`);
                console.log(`   ID: ${expense._id}`);
                console.log(`   类型: ${expense.type}`);
                console.log(`   里程: ${expense.mileage}km`);

                // 检查时间戳字段
                console.log(`   ⏰ 时间字段:`);
                console.log(`      创建时间: ${expense.createdAt} (${typeof expense.createdAt})`);
                console.log(`      更新时间: ${expense.updatedAt} (${typeof expense.updatedAt})`);
                console.log(`      费用日期: ${expense.date} (${typeof expense.date})`);

                // 检查统计信息
                if (expense.stats) {
                    console.log(`   📊 统计信息:`);
                    console.log(`      行驶里程: ${expense.stats.distance}km`);
                    console.log(`      百公里油耗: ${expense.stats.fuelConsumptionPer100km}L/100km`);
                    console.log(`      百公里费用: ${expense.stats.costPer100km}元/100km`);
                    console.log(`      消耗油量: ${expense.stats.fuelConsumption}L`);
                    console.log(`      上次里程: ${expense.stats.previousMileage}km`);
                    console.log(`      当前里程: ${expense.stats.currentMileage}km`);
                } else {
                    console.log(`   📊 统计信息: 无`);
                }

                // 检查fuelInfo（如果是加油记录）
                if (expense.type === '加油' && expense.fuelInfo) {
                    console.log(`   ⛽ 加油信息:`);
                    console.log(`      加油量: ${expense.fuelInfo.fuelAmount}L`);
                    console.log(`      表显金额: ${expense.fuelInfo.showAmount}元`);
                    console.log(`      实付金额: ${expense.fuelInfo.actualAmount || '未设置'}元`);
                }
            });

        } else {
            console.log('❌ 获取费用记录列表失败');
            console.log('状态码:', response.status);
            console.log('响应:', response.data);
        }

    } catch (error) {
        console.error('❌ 测试失败:', error.message);
        if (error.response) {
            console.error('响应状态:', error.response.status);
            console.error('响应数据:', error.response.data);
        }
    }
}

// 运行测试
if (require.main === module) {
    console.log('⚠️  注意: 请先确保:');
    console.log('   1. 服务器正在运行 (npm run dev)');
    console.log('   2. 更新 YOUR_TEST_TOKEN_HERE 为有效的认证token');
    console.log('   3. 确保数据库中有费用记录数据');
    console.log('');

    testExpensesStats();
}

module.exports = { testExpensesStats };
